import * as fs from "fs"
import initSqlJs from "sql.js"
import * as path from "path"

export class AugmentCleaner {
  /**
   * 清理数据库中带有 augment 的所有数据
   */
  async cleanAugmentData(dbPath: string): Promise<number> {
    console.log("=== AugmentCleaner.cleanAugmentData 开始 ===")
    console.log("dbPath:", dbPath)

    try {
      // 初始化sql.js
      const SQL = await initSqlJs({
        locateFile: (file: string) => {
          const wasmPath = path.join(__dirname, "..", "node_modules", "sql.js", "dist", file)
          return wasmPath
        }
      })

      // 读取数据库
      if (!fs.existsSync(dbPath)) {
        throw new Error(`数据库文件不存在: ${dbPath}`)
      }

      const dbBuffer = fs.readFileSync(dbPath)
      const db = new SQL.Database(dbBuffer)

      // 先查询有多少条augment数据
      const countResult = db.exec(
        "SELECT COUNT(*) as count FROM ItemTable WHERE key LIKE '%augment%'"
      )
      
      let deletedCount = 0
      if (countResult.length > 0 && countResult[0].values.length > 0) {
        deletedCount = countResult[0].values[0][0] as number
      }

      console.log(`找到 ${deletedCount} 条 Augment 数据`)

      // 执行删除操作
      if (deletedCount > 0) {
        db.run("DELETE FROM ItemTable WHERE key LIKE '%augment%'")
        console.log(`已删除 ${deletedCount} 条 Augment 数据`)
      }

      // 保存数据库
      const data = db.export()
      fs.writeFileSync(dbPath, Buffer.from(data))

      db.close()
      console.log("=== 清理 Augment 数据成功 ===")
      return deletedCount
    } catch (error) {
      console.error("=== 清理 Augment 数据失败 ===")
      console.error("错误详情:", error)
      throw error
    }
  }
}

